package org.cy.spring.learning.proxy.cglib;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib spring实现代理类
 *
 * create date: 2019/10/18 14:23
 *
 * @author cao.yong
 */
@Slf4j
public class CglibProxy implements MethodInterceptor {

    private Object target;

    public Object createProxyObject(Object obj) {
        this.target = obj;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(obj.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        log.info("Cglib 代理类: {}", proxy.getClass());
        return method.invoke(target, args);
    }
}
